<?
require_once('dpvr.logging.php');

function saveXML($simplexml) {
  global $config;
  $domDoc = new DomDocument('1.0', 'utf-8');
  $domDoc->formatOutput = true;
  $domDoc->preserveWhiteSpace = false;
  $domDoc->loadXml($simplexml->asXml());
  return file_put_contents($config['dpvr_dir'].'dpvr.xml', $domDoc->saveXml());
}

function convertFromHellaVCR () {

  if(file_exists($config['dpvr_dir'].'tv.xml')) {

    //create a SimpleXML object
    $hellaXML = simplexml_load_file($config['dpvr_dir'].'tv.xml');

    $dpvrXML = simplexml_load_string("<?xml version=\"1.0\"?>\n<tv></tv>\n");
    
    foreach ($hellaXML->xpath('/tv/show') as $hellaShow) {
    
      $show = $dpvrXML->addChild('show');
      
      print_log("Transferring $hellaShow->name");
      
      // find the tvdb ID. oddly enough by poster is the most reliable way to do it
      $num_matches = preg_match("/.*\/(\d+)\-(\d+)\.jpg/", $hellaShow->poster, $matches);
      
      if ($num_matches != 0) {
        $show->addAttribute('seriesID', $matches[1]);
        $show->addChild('poster', $hellaShow->poster);
      } else {
        $show->addAttribute('seriesID', '');
        $show->addChild('poster', '');
        $noID = true;
      }

      $show->addChild('seriesName', htmlspecialchars($hellaShow->name));
      $show->addChild('format', $hellaShow->format);
      $show->addChild('language', $hellaShow->language);
      $show->addChild('year', $hellaShow->year);
      $show->addChild('dlSeason', $hellaShow->season);
      $show->addChild('dlEpisode', $hellaShow->episode);
      $show->addChild('dfa', $hellaShow->dfa);
      $show->addChild('dfa_waiting', $hellaShow->dfa_waiting);
      
      if (!empty($hellaShow->downloads)) {
      
        $dl_node = $show->addChild('downloads', '');

        foreach ($hellaShow->downloads->download as $mydl) {

          $newdl = $dl_node->addChild('download', '');
          $dl_show = explode('x', $mydl->episode);
          $newdl->addChild('season', $dl_show[0]);
          $newdl->addChild('episode', (int)$dl_show[1]);
          $newdl->addChild('timestamp', $mydl->timestamp);

          // steal the timestamp from the latest one
          if ((int)$dl_show[0] == (int)$hellaShow->season && (int)$dl_show[1] == (int)$hellaShow->episode)
            $show->addChild('dlTimestamp', $mydl->timestamp);
        }
      }
    }
    
    saveXML($dpvrXML);
  }

  processTV();
}

if ($included_dpvr_xml_php !== true)
  convertFromHellaVCR();

?>
